/**
 * @Author: jichang
 * @Date: 2024/10/29 16:25:03
 * @LastEditors: jichang
 * @LastEditTime: 2024/10/29 16:25:03
 * Description: atmoic_flag实现 自旋锁
 * 
 * 自旋锁不会使线程陷入休眠，而是让线程不断地尝试获取锁，直到成功或超时。
 * 这种锁的特点在于等待过程中线程保持“活跃状态”，即自旋等待
 */
#include <atomic>
#include <vector>
#include <thread>
#include <iostream>

class spinlock_mutex {
public:
    spinlock_mutex(): flag(ATOMIC_FLAG_INIT) { }
    void lock() {
        // 一直检查是否为false
        while(flag.test_and_set(std::memory_order_acquire));
    }
    
    void unlock() {
        flag.clear(std::memory_order_release);
    }
private:    
    std::atomic_flag flag;
};

// 共享计数器和自旋锁
int counter = 0;
spinlock_mutex spinLock;

void increment(int iterations) {
    for (int i = 0; i < iterations; ++i) {
        spinLock.lock();    // 加锁保护计数器
        ++counter;          // 递增计数器
        spinLock.unlock();  // 解锁
    }
}

int main() {
    const int numThreads = 10;    // 线程数量
    const int incrementsPerThread = 1000;  // 每个线程的递增次数

    // 创建并启动线程
    std::vector<std::thread> threads;
    for (int i = 0; i < numThreads; ++i) {
        threads.emplace_back(increment, incrementsPerThread);
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    // 输出结果
    std::cout << "Final counter value: " << counter << std::endl;
    std::cout << "Expected counter value: " << numThreads * incrementsPerThread << std::endl;

    return 0;
}